package com.xinyan.study;

import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author xinyan.xie
 * @description
 * @date 2020/9/14
 */
public class RedisClusterTest {
    private static JedisCluster jedis;
    static {
        // 添加集群的服务节点Set集合
        Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();
        // 添加节点
        hostAndPortsSet.add(new HostAndPort("123.56.41.78", 7001));
        hostAndPortsSet.add(new HostAndPort("123.56.41.78", 7002));
        hostAndPortsSet.add(new HostAndPort("123.56.41.78", 7003));
        hostAndPortsSet.add(new HostAndPort("123.56.41.78", 7004));
        hostAndPortsSet.add(new HostAndPort("123.56.41.78", 7005));
        hostAndPortsSet.add(new HostAndPort("123.56.41.78", 7006));

        // Jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲连接数, 默认8个
        jedisPoolConfig.setMaxIdle(1);
        // 最大连接数, 默认8个
        jedisPoolConfig.setMaxTotal(50);
        //最小空闲连接数, 默认0
        jedisPoolConfig.setMinIdle(0);
        // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(2000); // 设置2秒
        //对拿到的connection进行validateObject校验
        jedisPoolConfig.setTestOnBorrow(true);
        jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig);
    }

    /**
     * 测试key:value数据
     */
    @Test
    public void testKey() throws InterruptedException {
        System.out.println("判断某个键是否存在："+jedis.exists("username"));
        System.out.println("新增<'username','wukong'>的键值对："+jedis.set("username", "timo"));
        System.out.println("是否存在:"+jedis.exists("username"));

        System.out.println("新增<'password','password'>的键值对："+jedis.set("password", "123456"));
        System.out.println("删除键password:"+jedis.del("password"));
        System.out.println("判断键password是否存在："+jedis.exists("password"));
        System.out.println("设置键username的过期时间为10s:"+jedis.expire("username", 10));
        TimeUnit.SECONDS.sleep(2); // 线程睡眠2秒
        System.out.println("查看键username的剩余生存时间："+jedis.ttl("username"));
        Thread.sleep(1000);
        System.out.println("查看键username的剩余生存时间："+jedis.ttl("username"));
        System.out.println("移除键username的生存时间："+jedis.persist("username"));
        System.out.println("查看键username的剩余生存时间："+jedis.ttl("username"));
        System.out.println("查看键username所存储的值的类型："+jedis.type("username"));
    }
}
